package com.zhht.htzx.ui;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.JsonObject;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.binding_recyclerview.adapter.SimpleDataBindingAdapter;
import com.nsgf.library.data.bean.OrderDetailBean;
import com.nsgf.library.data.bean.OrderListBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.zhht.htzx.BR;
import com.zhht.htzx.R;
import com.zhht.htzx.adapter.OrderItemAdapter;
import com.zhht.htzx.databinding.ActivityOrderDetailBinding;
import com.zhht.htzx.databinding.ItemOrderBinding;
import com.zhht.htzx.databinding.ItemOrderProductBinding;
import com.zhht.htzx.utils.QRCodeGenerator;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 订单详情Activity
 */
public class OrderDetailActivity extends BaseActivity {

    private String orderId;

    private OrderDetailStateHolder mStates;

    private AccountRequester mAccountRequester;

    private SimpleDataBindingAdapter<OrderListBean.ListBean.ItemsBean, ItemOrderProductBinding> mAdapter;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(OrderDetailStateHolder.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    private ActivityOrderDetailBinding mBinding;

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new SimpleDataBindingAdapter<OrderListBean.ListBean.ItemsBean, ItemOrderProductBinding>(this,
                R.layout.item_order_product, new DiffUtil.ItemCallback<OrderListBean.ListBean.ItemsBean>() {
            @Override
            public boolean areItemsTheSame(@NonNull OrderListBean.ListBean.ItemsBean oldItem, @NonNull OrderListBean.ListBean.ItemsBean newItem) {
                return false;
            }

            @Override
            public boolean areContentsTheSame(@NonNull OrderListBean.ListBean.ItemsBean oldItem, @NonNull OrderListBean.ListBean.ItemsBean newItem) {
                return false;
            }
        }) {
            @Override
            protected void onBindItem(ItemOrderProductBinding binding, OrderListBean.ListBean.ItemsBean item, RecyclerView.ViewHolder holder) {
                binding.setVm(item);
                if (mStates.orderDetailState.get().getStatus() == 10) {
                    if (item.getAfterSaleStatus() == 0) {
                        binding.tvItemOrderRefund.setVisibility(VISIBLE);
                    } else {
                        binding.tvItemOrderRefund.setVisibility(GONE);
                    }
                } else {
                    binding.tvItemOrderRefund.setVisibility(GONE);
                }
                binding.tvItemOrderRefund.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        JsonObject params = new JsonObject();
                        params.addProperty("orderItemId", item.getId());
                        params.addProperty("refundPrice", item.getPayPrice());
                        params.addProperty("way", "10");
                        params.addProperty("applyReason", "待发货退款");
                        mAccountRequester.refundOrder(params);
                    }
                });
            }
        };
        return new DataBindingConfig(R.layout.activity_order_detail, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy())
                .addBindingParam(BR.adapter, mAdapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (ActivityOrderDetailBinding) getBinding();
        getLifecycle().addObserver(mAccountRequester);
        mStates.titleBar.set("订单详情");
        initData();
        loadOrderDetail();
    }

    public static class OrderDetailStateHolder extends StateHolder {

        public final State<OrderDetailBean> orderDetailState = new State<>(new OrderDetailBean());

    }

    private void initData() {
        orderId = getIntent().getStringExtra("orderId");
        mAccountRequester.getOrderDetails(orderId);

        mAccountRequester.getSrcSuccess().observe(this, new Observer<ResponseStatus<String>>() {
            @Override
            public void onChanged(ResponseStatus<String> stringResponseStatus) {
                if (stringResponseStatus.getResponseCode() == 0) {
                    showToast(stringResponseStatus.getMsg());
                    finish();
                }
            }
        });
    }

    private void loadOrderDetail() {

        mAccountRequester.getOrderDetailResult().observe(this, new Observer<ResponseStatus<OrderDetailBean>>() {
            @Override
            public void onChanged(ResponseStatus<OrderDetailBean> orderDetailBeanResponseStatus) {

                if (orderDetailBeanResponseStatus.getResponseCode() == 0) {
                    mStates.orderDetailState.set(orderDetailBeanResponseStatus.getData());
                    if (mStates.orderDetailState.get().getStatus() == 0) {
                        mBinding.btnSecondary.setVisibility(VISIBLE);
                        mBinding.llOrderDetailCode.setVisibility(GONE);
                    } else if (mStates.orderDetailState.get().getStatus() == 40
                            || mStates.orderDetailState.get().getRefundStatus() == 20) {
                        mBinding.btnOrderDetailDelete.setVisibility(VISIBLE);
                        mBinding.llOrderDetailCode.setVisibility(GONE);
                    } else if (mStates.orderDetailState.get().getStatus() == 30) {
                        mBinding.llOrderDetailCode.setVisibility(VISIBLE);
                        setupQRCode();
                    } else {
                        mBinding.btnSecondary.setVisibility(GONE);
                    }
                    if (mStates.orderDetailState.get().getStatus() == 10) {

                        mBinding.llOrderDetailCode.setVisibility(GONE);
                        if (!mStates.orderDetailState.get().getItems().isEmpty()) {
                            for (OrderListBean.ListBean.ItemsBean itemsBean : mStates.orderDetailState.get().getItems()) {
                                if (itemsBean.getAfterSaleStatus() == 0 && mStates.orderDetailState.get().getDeliveryType() != 1) {
                                    mBinding.llOrderDetailCode.setVisibility(VISIBLE);
                                    setupQRCode();
                                    return;
                                }

                            }
                        }

                    }
                }
            }
        });
        updateUI();
    }

    private void updateUI() {

        // 设置按钮
        setupButtons();
    }

    private void setupQRCode() {
        // 只在待付款状态下显示二维码
        mBinding.ivQrCode.setVisibility(VISIBLE);
        // 生成二维码
        Bitmap qrBitmap = QRCodeGenerator.generateQRCode(orderId, 512);
        if (qrBitmap != null) {
            mBinding.ivQrCode.setImageBitmap(qrBitmap);
        }

    }


    public class ClickProxy {
        public void deleteOrder() {
            mAccountRequester.deleteOrder(orderId);
        }

        public void cancelOrder() {
            mAccountRequester.cancelOrder(orderId);
        }
    }

    private void setupButtons() {
//
//        switch (currentOrder.getStatus()) {
//            case PENDING:
//                btnPrimary.setText("立即付款");
//                btnSecondary.setText("取消订单");
//                break;
//
//            case PAID:
//                btnPrimary.setText("查看物流");
//                btnSecondary.setText("申请退款");
//                break;
//
//            case SHIPPED:
//                btnPrimary.setText("确认收货");
//                btnSecondary.setText("查看物流");
//                break;
//
//            case DELIVERED:
//                btnPrimary.setText("确认收货");
//                btnSecondary.setText("申请退款");
//                break;
//
//            case COMPLETED:
//                btnPrimary.setText("再次购买");
//                btnSecondary.setText("申请退款");
//                btnSecondary.setVisibility(currentOrder.canRefund() ? View.VISIBLE : View.GONE);
//                break;
//
//            case CANCELLED:
//            case REFUNDED:
//                btnPrimary.setText("再次购买");
//                btnSecondary.setVisibility(View.GONE);
//                break;
//
//            case REFUNDING:
//                btnPrimary.setText("查看退款进度");
//                btnSecondary.setVisibility(View.GONE);
//                break;
//        }

        // 设置按钮点击事件
//        btnPrimary.setOnClickListener(v -> handlePrimaryButtonClick());
//        btnSecondary.setOnClickListener(v -> handleSecondaryButtonClick());
    }
//
//    private void handlePrimaryButtonClick() {
//        switch (currentOrder.getStatus()) {
//            case PENDING:
//                handlePayment();
//                break;
//            case DELIVERED:
//                showConfirmDeliveryDialog();
//                break;
//            default:
//                Toast.makeText(this, "功能开发中", Toast.LENGTH_SHORT).show();
//                break;
//        }
//    }
//
//    private void handleSecondaryButtonClick() {
//        switch (currentOrder.getStatus()) {
//            case PENDING:
//                showCancelOrderDialog();
//                break;
//            case PAID:
//            case SHIPPED:
//            case DELIVERED:
//            case COMPLETED:
//                handleRefund();
//                break;
//            default:
//                Toast.makeText(this, "功能开发中", Toast.LENGTH_SHORT).show();
//                break;
//        }
//    }
//
//    private void handlePayment() {
//        // 这里应该跳转到支付页面
//        Toast.makeText(this, "跳转到支付页面", Toast.LENGTH_SHORT).show();
//
//        // 模拟支付成功
//        orderManager.updateOrderStatus(currentOrder.getOrderId(), Order.OrderStatus.PAID);
//        loadOrderDetail();
//    }
//
//    private void showCancelOrderDialog() {
//        new AlertDialog.Builder(this)
//                .setTitle("取消订单")
//                .setMessage("确定要取消这个订单吗？")
//                .setPositiveButton("确定", (dialog, which) -> {
//                    orderManager.updateOrderStatus(currentOrder.getOrderId(), Order.OrderStatus.CANCELLED);
//                    Toast.makeText(this, "订单已取消", Toast.LENGTH_SHORT).show();
//                    loadOrderDetail();
//                })
//                .setNegativeButton("取消", null)
//                .show();
//    }
//
//    private void showConfirmDeliveryDialog() {
//        new AlertDialog.Builder(this)
//                .setTitle("确认收货")
//                .setMessage("确认已收到商品吗？")
//                .setPositiveButton("确认", (dialog, which) -> {
//                    orderManager.updateOrderStatus(currentOrder.getOrderId(), Order.OrderStatus.COMPLETED);
//                    Toast.makeText(this, "确认收货成功", Toast.LENGTH_SHORT).show();
//                    loadOrderDetail();
//                })
//                .setNegativeButton("取消", null)
//                .show();
//    }
//
//    private void handleRefund() {
//        // 这里应该跳转到退款页面
//        Toast.makeText(this, "跳转到退款页面", Toast.LENGTH_SHORT).show();
//
//        // 模拟申请退款
//        orderManager.updateOrderStatus(currentOrder.getOrderId(), Order.OrderStatus.REFUNDING);
//        loadOrderDetail();
//    }
//
//    private void shareOrder() {
//        if (currentOrder == null) return;
//
//        String shareText = "我的订单\n";
//        shareText += "订单号：" + currentOrder.getOrderId() + "\n";
//        shareText += "状态：" + currentOrder.getStatusDisplayText() + "\n";
//        shareText += "金额：¥" + String.format("%.2f", currentOrder.getActualAmount()) + "\n";
//        shareText += "下单时间：" + dateFormat.format(currentOrder.getCreateTime());
//
//        Intent shareIntent = new Intent(Intent.ACTION_SEND);
//        shareIntent.setType("text/plain");
//        shareIntent.putExtra(Intent.EXTRA_TEXT, shareText);
//        startActivity(Intent.createChooser(shareIntent, "分享订单"));
//    }
} 